const {
  globalData
} = getApp();
const {
  intDate,
  formatNumber
} = require('../../utils/util.js')

const {attendMenology} = require('../../api/geData.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null,
    courseData: null,
    currentMonth: null,
    curToday:'',
    nowMonth: null,
    toDay: null,
    schooltime: { // 上课时间
      top: false,
      middle: false,
      bottom: false
    },
    cardRecord: {
      // time: '9:30',
      // beLate: true, // 迟到
      // truant: true, // 旷课
      // upCard: true // 补卡
    },
    coverData: [],
    showCover: false,
    formerIndex: null,
    claState: null,
    noDaka:false,
    isArrangingCourse:true,
    orderTime:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let coverMonthList = wx.getStorageSync('calendarAllData').coverMonthList,
      courseData = wx.getStorageSync('calendarAllData').courseData,
      calendarData = wx.getStorageSync('calendarAllData').calendarData,
      coverData = [],
      that = this
   
    let fromDay = {
      year: new Date(courseData.classBegin*1).getFullYear(),
      month: new Date(courseData.classBegin*1).getMonth(),
      day: new Date(courseData.classBegin*1).getDate()
    }

    let toDay = {
      year: new Date(courseData.classEnd*1).getFullYear(),
      month: new Date(courseData.classEnd*1).getMonth(),
      day: new Date(courseData.classEnd*1).getDate()
    }

    coverMonthList.map((item, index) =>{
      let itemData = {}
      itemData.month = item.month.split('-')[0] + '年' + item.month.split('-')[1]+'月'
      itemData.showTick = item.showTick
      if (item.showTick){
        that.setData({
          nowMonth: itemData
        })
      }
      coverData.push(itemData)
    })
    


    intDate(this, fromDay, toDay)

    let dates = this.data.dates

    dates.map((item, index) => {

      if (item[0].month == this.data.nowMonth.month){
        this.formatGetData(calendarData, item)
      }
    })


    this.setData({
      userInfo: globalData.userInfo,
      courseData: wx.getStorageSync('calendarAllData').courseData,
      coverData: coverData,
      toDay: wx.getStorageSync('time'),
      claState : wx.getStorageSync('claState')
    })

    dates.map((item,index)=>{
      let data = {}
      data.month = item[0].month
      data.showIcon =false
      if (index =='0'){
        data.showIcon = true
      }
      // coverData.push(data)
    })

    this.setData({
      // coverData: coverData
    })
    // console.log(this.data.dates)
  },

  // 月份蒙版点击事件
  coverCheck(e) {
    let index = e.currentTarget.dataset.index
    // 点击原来index不请求
    if (this.data.formerIndex == index) {
      this.setData({
        showCover: false
      })
      return
    }

    let coverData = this.data.coverData,
      month = wx.getStorageSync('calendarAllData').coverMonthList,
      that = this

    coverData.map((item, idx) => {
      item.showTick = false
      if(index == idx ){
        item.showTick = true
      }
    })

    attendMenology(wx.getStorageSync('userInfo').cluesOrStuId, this.data.courseData.formalClassId, month[index].month.split('-').join('')).then(res => {
      that.data.dates.map((item) => {
        if (item[index].month == that.data.nowMonth.month) {
          that.formatGetData(res.attendMenology, item)
        }
      })
    })

    this.setData({
      coverData: coverData,
      nowMonth: coverData[index],
      showCover: false,
      formerIndex: index
    })
  },

  // 格式化返回日历的数据
  formatGetData(calendarData, data) {
    // console.log(calendarData)
    // console.log(data)
    let time = {
      top: wx.getStorageSync('claState')[0].value.split('-')[1],
      middle: wx.getStorageSync('claState')[1].value.split('-')[1],
      bottom: wx.getStorageSync('claState')[2].value.split('-')[1]
    },
    stmp = new Date().getTime(),
    toDay = wx.getStorageSync('time').split('-').join('/');
    data.map((val) => {
      // 判断是否为今天日期，加蓝框
      let tt = new Date(val.date).getTime();
      let tt2 = new Date(wx.getStorageSync('time').split('-').join('/')).getTime();
      if (tt == tt2)
      {
        let date = wx.getStorageSync('time').split('-').join('/')
        let darr=date.split('/');
        this.setData({
          curToday: darr[2]
        })
      }
      calendarData.map((item) => {
        let date = new Date(item.attendDate),
          year = date.getFullYear(),
          month = date.getMonth() + 1,
          day = date.getDate();

        if ((year + '/' + month+'/'+ day) == val.date){
          let format = this.format(item.state);
          val.orderTime[format] = {
            status: item.status,
            starttime: item.starttime,
            endtime: item.endtime,
            time: item.punchDate && (new Date(item.punchDate).getHours() + ':' + formatNumber(new Date(item.punchDate).getMinutes())) || false,
            classTime: time[format]
          }

          if ((year + '/' + month + '/' + day) == toDay && val.orderTime[format].status == '未打卡'){
            let toDayStmp = new Date(`${year}/${month}/${day}/ ${time[format]}`).getTime()
            if (stmp > toDayStmp){
              val.orderTime[format].status = '旷课'
            }
          }
        }
      })
      
      let orderTime = val.orderTime;
      for (let key in orderTime){
        if (orderTime[key] && orderTime[key].status != '未打卡'){
          if (orderTime[key].status == '迟到' || orderTime[key].status == '旷课' || orderTime[key].status == '请假'){
            val.className = 'dataOrange'
            break
          }
          val.className = 'dataDlue'
        }
      }

    })

    this.setData({
      currentMonth: data
    })
  },

  // 处理早中晚数据
  format(item){
    const actions = new Map([
      ['早','top'],
      ['中', 'middle'],
      ['晚', 'bottom'],
    ])

    return actions.get(item)
  },

  // 点击月份显示蒙版
  showCover(){
    if (this.data.coverData.length * 1 <= 1) return
    this.setData({
      showCover: true
    })
  },
  showCoverFn(){
    this.setData({
      showCover: false
    })
  },

  // 选择日期
  toChooseDay(e){
    let checkDay =e.currentTarget.dataset.checkDay,
      currentMonth = this.data.currentMonth,
      item = e.currentTarget.dataset.item,
      orderTime = {},
      cardRecord = {}

    // console.log(item)

    // 判断当前选中的日期是否大于今天的日期
    let chooseDate = new Date(checkDay.date).getTime() 
    let tday = new Date(wx.getStorageSync('time').split('-').join('/')).getTime()
    if (chooseDate>tday)
    {
      this.setData({
        noDaka:true
      })
    }else{
      this.setData({
        noDaka: false
      })
    }

    // 不在日期内不执行
    !checkDay.inDate && true

    currentMonth.map((item,index) => {
      if (item.date == checkDay.date){
        item.choosed = !item.choosed
        orderTime = item.choosed && checkDay.orderTime || {}
      } else {
        item.choosed = false
      }
    })
    
    // 判断是否有排课
    let isArrangingCourse=''
    if (item.orderTime.top || item.orderTime.middle || item.orderTime.bottom){
      isArrangingCourse=true;
    }else{
      isArrangingCourse =false;
    }
    // console.log(orderTime)
    if (JSON.stringify(orderTime)!='{}'){
      this.setData({
        orderTime: orderTime
      })
    }
    this.setData({
      cardRecord: item,
      currentMonth: currentMonth,
      schooltime: orderTime,
      isArrangingCourse: isArrangingCourse
    })

    // console.log(this.data.cardRecord)
  },

  // 点击日期跟着换数据函数



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  }
})